package com.zhangruile.web.servlet;

/**
 * ClassName: BaseServlet
 *
 * @author :张蕊乐
 *         version :
 * @since JDK 1.8
 * date: 2017 11 10 10:05
 */
import com.zhangruile.web.annotation.RequestMapping;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class BaseServlet extends HttpServlet{
    /**
     * 保存URL 与method之间的映射关系
     */
    private Map<String,Method> requestMappings=new HashMap<String, Method>();

    /**
     * 初始化的时候解析 @RequestMapping
     * 从@RequestMapping中取出url与@WebServlet 中定义的url合并成一个完成的url
     * 然后在将url 对应的method 放到一个map中保存起来
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        //取得当前Servlet类的Class对象
        Class clsServlet=this.getClass();
        //取得WebServlet 对象获取基础的url
        WebServlet webServlet=(WebServlet)clsServlet.getAnnotation(WebServlet.class);
        String baseUrl=webServlet.value()[0];

        //反射取得所有的方法
        Method[] methods=clsServlet.getDeclaredMethods();
        for (Method method : methods) {
            //查看方法上是否标注了 @RequestMapping
            if(method.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping=method.getAnnotation(RequestMapping.class);
                //获取url
                String url=requestMapping.value();
                if(!url.startsWith("/")) {
                    url="/"+url;
                }
                String fullUrl=baseUrl.replace("/*","")+url;
                //保存到Map上
                requestMappings.put(fullUrl,method);
            }

        }

        System.out.println(requestMappings);


    }
    //由于请求转发地址需要重复使用，所以单独提出来
    private  static final  String PREFIX="/WEB-INF/views";
    private static final String SUFFIX=".jsp";

    protected void toView(HttpServletRequest request,HttpServletResponse response, String viewName) throws ServletException, IOException {
        request.getRequestDispatcher(PREFIX+viewName+SUFFIX).forward(request,response);
    }
    protected void redirectTo(HttpServletResponse response, String url) throws ServletException, IOException {
        String contextPath=super.getServletContext().getContextPath();
        if(!url.startsWith("/")){
            url+="/";
        }
        response.sendRedirect(contextPath+url);
    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //取得当前请求的url
        String requestURl=req.getRequestURI();
        //从map中取得方法
        Method method=requestMappings.get(requestURl);
        if(method==null) {
            resp.sendError(404,"请求路径错误");

            return;
        }
        //调用方法法
        try {
            method.invoke(this, req,resp);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}
